package ${g.codePackage}.service;
import ${g.codePackage}.util.RedisUtil;
import ${g.codePackage}.exception.ValidataException;
import com.beust.jcommander.internal.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
@Component
public class BaseService {

    @Resource
    protected HttpServletRequest request;

    @Resource
    protected HttpServletResponse response;

    @Autowired
    protected RedisUtil redisUtil;

    @Autowired
    private Validator validator;

    /**
    * 校验对象
    * @param object
    *            待校验对象
    * @param groups
    *            待校验的组
    * @return message 验证信息
    *
    */
    public void beanValidator(Object object, Class<?>... groups) throws Exception {
        Set< ConstraintViolation<Object> > constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            List<String> list = Lists.newArrayList();
            Iterator< ConstraintViolation<Object> > iterator = constraintViolations.iterator();
            while (iterator.hasNext()) {
                String message = iterator.next().getMessage();
                list.add(message);
            }
            if (list != null && list.size() > 0) {
                throw new ValidataException(list.get(0));
            }
        }
    }
}